package com.tengju.bff.interfaces.covercharge.controller.provider;

import com.alibaba.fastjson.JSON;
import com.idanchuang.component.base.JsonResult;
import com.idanchuang.component.redis.util.DRedisLocks;
import com.tengju.bff.interfaces.covercharge.constant.*;
import com.tengju.bff.interfaces.covercharge.dto.*;
import com.tengju.bff.interfaces.covercharge.entity.vo.AdminSelfCertificationQueryVo;
import com.tengju.bff.interfaces.covercharge.intf.IWithdrawalProvider;
import com.tengju.bff.interfaces.covercharge.service.IAdminApplyRecordService;
import com.tengju.bff.interfaces.covercharge.service.LeTaxOneService;
import com.tengju.bff.interfaces.covercharge.service.IServiceLetaxWithdrawLogService;
import com.tengju.bff.interfaces.covercharge.service.IServiceSelfCertificationWithdrawService;
import com.tengju.bff.interfaces.shared.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.tengju.bff.interfaces.covercharge.entity.vo.WithdrawRecordVo;

import java.util.List;

@Slf4j
@Service("withdrawalProvider")
public class WithdrawalProvider implements IWithdrawalProvider {

    @Autowired
    @Lazy
    private LeTaxOneService leTaxOneService;

    @Autowired
    IServiceLetaxWithdrawLogService serviceLetaxWithdrawLogService;

    @Autowired
    IServiceSelfCertificationWithdrawService serviceSelfCertificationWithdrawService;

    @Autowired
    @Lazy
    private IAdminApplyRecordService adminApplyRecordService;

    /**
     * 功能描述: <br>
     * 取消服务费提现申请
     *
     * @param withdrawalCancel 提现申请取消
     */
    @Override
    public ApiResponse<Integer> cancelWithdrawalApply(@RequestBody WithdrawalCancel withdrawalCancel) {
        log.info("取消服务费提现申请...{}", JSON.toJSONString(withdrawalCancel));
        Assert.notNull(withdrawalCancel.getIdCode(), "idCode不能为空");
        Assert.hasText(withdrawalCancel.getPlatformCode(), "平台编号不能为空");
        Assert.isTrue(CoverChargeEnum.ServiceAccountType.MANAGE_TYPE.getPlatform().equals(withdrawalCancel.getPlatformCode()), "平台编号不正确");

        Assert.hasText(withdrawalCancel.getCurrentIdentity(), "当前身份不能为空");
        Assert.isTrue(SignIdentityEnum.person.toString().equals(withdrawalCancel.getCurrentIdentity())
                || SignIdentityEnum.regist_soho.toString().equals(withdrawalCancel.getCurrentIdentity()), "当前身份不正确");

        return DRedisLocks.runWithLock(BizConstants.WITHDRAWAL_CANCEL + withdrawalCancel.getIdCode(), 500, () -> {
            try {
                WithdrawalCancelEnum withdrawalCancelEnum;
                if (WithdrawalCancelEnum.end.toString().equals(withdrawalCancel.getType())) {
                    withdrawalCancelEnum = WithdrawalCancelEnum.end;
                } else {
                    withdrawalCancelEnum = WithdrawalCancelEnum.upgrade;
                }
                int count = leTaxOneService.withdrawalApplyCancel(withdrawalCancel.getIdCode(), withdrawalCancel.getPlatformCode(), null, withdrawalCancelEnum);
                return ApiResponse.newSuccess(count);
            } catch (Exception e) {
                log.error("cancelWithdrawalApply error", e);
                return ApiResponse.newFailure(CoverChargeErrorCode.SYS_ERROR.getCode(), e.getMessage());
            }
        });
    }

    /**
     * 功能描述: <br>
     * 个人升级乐税个体户/个人修改收款账户，修改服务费提现申请
     *
     * @param withdrawalModify 提现申请修改
     */
    @Override
    public ApiResponse<?> modifyWithdrawalApply(WithdrawalModify withdrawalModify) {
        log.info("修改服务费提现申请...{}", JSON.toJSONString(withdrawalModify));
        Assert.notNull(withdrawalModify.getIdCode(), "idCode不能为空");
        Assert.hasText(withdrawalModify.getPlatformCode(), "平台编号不能为空");
        Assert.isTrue(CoverChargeEnum.ServiceAccountType.MANAGE_TYPE.getPlatform().equals(withdrawalModify.getPlatformCode()), "平台编号不正确");

        Assert.hasText(withdrawalModify.getCurrentIdentity(), "当前身份不能为空");
        if (withdrawalModify.getWithdrawLogId() == null) {
            Assert.isTrue(SignIdentityEnum.person.toString().equals(withdrawalModify.getCurrentIdentity()), "当前身份不正确");
        }

        if (CoverChargeEnum.CommonStatus.YES.getCode().equals(withdrawalModify.getFlag())) {
            Assert.notNull(withdrawalModify.getBankInfo(), "收款账户信息不能为空");
            BankInfo bankInfo = withdrawalModify.getBankInfo();
//            Assert.hasText(bankInfo.getBankName(),"开户行名称不能为空");
            Assert.hasText(bankInfo.getBankNo(), "银行卡号不能为空");
            Assert.hasText(bankInfo.getIdcardName(), "户名不能为空");
            Assert.hasText(bankInfo.getIdcardNo(), "身份证号码不能为空");
        }

        return DRedisLocks.runWithLock(BizConstants.WITHDRAWAL_MODIFY + withdrawalModify.getIdCode(), 500, () -> {
            try {
                leTaxOneService.withdrawalApplyModify(withdrawalModify);
                return ApiResponse.newSuccess();
            } catch (Exception e) {
                log.error("modifyWithdrawalApply error", e);
                return ApiResponse.newFailure(CoverChargeErrorCode.SYS_ERROR.getCode(), e.getMessage());
            }
        });
    }

    /**
     * 功能描述: <br>
     * 个体户提现记录
     *
     * @param withdrawalRecord 个体户提现记录
     */
    @Override
    public ApiResponse<List<WithdrawRecordVo>> registeredSohoWithdrawalRecord(WithdrawalRecord withdrawalRecord) {
        Assert.notNull(withdrawalRecord.getIdCode(), "idCode不能为空");
        Assert.hasText(withdrawalRecord.getPlatformCode(), "平台编号不能为空");
        Assert.hasText(withdrawalRecord.getType(), "身份类型不能为空");
        Assert.isTrue(CoverChargeEnum.ServiceAccountType.MANAGE_TYPE.getPlatform().equals(withdrawalRecord.getPlatformCode()), "平台编号不正确");

        try {
            List<WithdrawRecordVo> resultList = serviceLetaxWithdrawLogService.withdrawListByTime(withdrawalRecord.getIdCode(), withdrawalRecord.getPlatformCode(), withdrawalRecord.getType(), withdrawalRecord.getStartTime(), withdrawalRecord.getEntTime());
            return ApiResponse.newSuccess(resultList);
        } catch (Exception e) {
            log.error("registeredSohoWithdrawal error", e);
            return ApiResponse.newFailure(CoverChargeErrorCode.SYS_ERROR.getCode(), e.getMessage());
        }
    }

    /**
     * 功能描述: <br>
     * 认证提现记录
     *
     * @param certificationWithdrawalRecord 认证提现记录
     */
    @Override
    public ApiResponse<List<AdminSelfCertificationQueryVo>> certificationWithdrawalRecord(CertificationWithdrawalRecord certificationWithdrawalRecord) {
        Assert.notNull(certificationWithdrawalRecord.getIdCode(), "idCode不能为空");
        Assert.notNull(certificationWithdrawalRecord.getType(), "身份类型不能为空");
        Assert.hasText(certificationWithdrawalRecord.getPlatformCode(), "平台编号不能为空");
        Assert.isTrue(CoverChargeEnum.ServiceAccountType.MANAGE_TYPE.getPlatform().equals(certificationWithdrawalRecord.getPlatformCode()), "平台编号不正确");

        try {
            List<AdminSelfCertificationQueryVo> resultList = serviceSelfCertificationWithdrawService.withdrawListByTime(certificationWithdrawalRecord.getIdCode(), certificationWithdrawalRecord.getPlatformCode(), certificationWithdrawalRecord.getType(), certificationWithdrawalRecord.getStartTime(), certificationWithdrawalRecord.getEntTime());
            return ApiResponse.newSuccess(resultList);
        } catch (Exception e) {
            log.error("certificationWithdrawalRecord error", e);
            return ApiResponse.newFailure(CoverChargeErrorCode.SYS_ERROR.getCode(), e.getMessage());
        }
    }

    /**
     * 功能描述: <br>
     * 提现拒绝
     *
     * @param refusedToWithdraw 提现拒绝
     */
    @Override
    public ApiResponse<?> refusedToWithdrawApply(RefusedToWithdraw refusedToWithdraw) {
        Assert.notNull(refusedToWithdraw.getApplyId(), "申请id不能为空");
        Assert.notNull(refusedToWithdraw.getRemark(), "拒绝理由不能为空");
        Assert.notNull(refusedToWithdraw.getStatus(), "状态不能为空");

        return DRedisLocks.runWithLock(BizConstants.UPDATE_APPLY_REG + refusedToWithdraw.getApplyId(), 500, () -> {
            try {
                adminApplyRecordService.updateRegistrationStatus(refusedToWithdraw.getApplyId(), refusedToWithdraw.getRemark(), refusedToWithdraw.getStatus(), refusedToWithdraw.getApprovers());
                return ApiResponse.newSuccess();
            } catch (Exception e) {
                log.error("refusedToWithdrawApply error", e);
                return ApiResponse.newFailure(CoverChargeErrorCode.SYS_ERROR.getCode(), e.getMessage());
            }
        });
    }

    @Override
    public ApiResponse<Boolean> queryIsExistLeTaxWithdraw(@RequestParam("idCode") Long idCode) {
        Assert.notNull(idCode, "idCode不能为空");
        return ApiResponse.newSuccess(serviceLetaxWithdrawLogService.isExistLeTaxWithdraw(idCode));
    }

    @Override
    public ApiResponse<Boolean> queryIsExistSelfCerWithdraw(@RequestParam("idCode") Long idCode) {
        Assert.notNull(idCode, "idCode不能为空");
        return ApiResponse.newSuccess(serviceSelfCertificationWithdrawService.isExistSelfCertWithdraw(idCode));
    }


}
